<template>
  <div class="regist-container">
    <div class="registpage-top">
      <el-dialog class="loginForm" :visible.sync="dialogVisible" :modal-append-to-body='false'>
        <div v-for="item in picture" :key="item.id">
          <img :src="item" style="width:100%;" />
        </div>
      </el-dialog>
    </div>
    <div class="regist-div">
      <div class="regist">
        <div class="dataForm-title">按照审核意见修改您的机构信息</div>
        <el-alert title="审核意见" :description="dataForm.checkWord" type="warning" :closable="false" show-icon style="margin-bottom:10px;"></el-alert>
        <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="right" label-width="100px">
          <el-form-item label="机构名称" prop="name">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item label="机构简介" prop="nickName">
            <el-input v-model="dataForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="机构分类" prop="mcategoryId">
            <el-select v-model="dataForm.mcategoryId">
              <el-option v-for="item in mcategory" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域地址">
            <el-select v-model="dataForm.provinceId" placeholder="省" @change="provinceChange">
              <el-option v-for="item in provinces" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.cityId" placeholder="市" @change="cityChange">
              <el-option v-for="item in cities" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.areaId" placeholder="区" @change="areaChange">
              <el-option v-for="item in areas" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="具体位置" prop="address">
            <el-input v-model="dataForm.address"></el-input>
          </el-form-item>
          <el-form-item label="法人" prop="legalPerson">
            <el-input v-model="dataForm.legalPerson"></el-input>
          </el-form-item>
          <el-form-item label="联系号码" prop="telephone">
            <el-input v-model="dataForm.telephone"></el-input>
          </el-form-item>
          <el-form-item label="上传资质" prop="certification">
            <el-upload :action='uploadPaths' :limit='5' multiple accept=".jpg,.jpeg,.png,.gif" :file-list="galleryFileList" list-type="picture-card" :on-exceed='uploadOverrun' :on-success="handleGalleryUrl" :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- <el-upload class="certification-uploader" :action='uploadPaths' :file-list="galleryFileList" list-type="picture-card" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif" :on-exceed='uploadOverrun' :on-success="handleGalleryUrl" :on-remove="handleRemove">
              <img v-if="dataForm.certification" :src="dataForm.certification" class="certification">
              <i v-else class="el-icon-plus certification-uploader-icon"></i>
            </el-upload> -->
          </el-form-item>
          <el-form-item prop="checked" style="width: 400px;">
            <el-checkbox label="我已阅读，同意并遵守爱联商圈合同" v-model="checked"></el-checkbox>
            <div class="contract" @click="getContract">查看详情</div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" style="margin-left:25%;width:50%;" @click="createData" :disabled="this.checked===false">提交信息重新审核</el-button>
        </div>
      </div>
    </div>
    <div class="registpage-footer"></div>
  </div>
</template>
<script>
import { queryalipaystatus } from '@/api/user'
import { queryMechanismMeg, updateMechanismProxy } from '@/api/mechanism'
import { listAllMCategory } from '@/api/login'
import { queryPicurl } from '@/api/proxy'
import { listSubRegion, listAddress } from '@/api/region'
import VueQr from 'vue-qr'
import { createStorageFile, uploadPaths } from '@/api/storage'

export default {
  components: { VueQr },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else {
        var reg = /^1[3456789]\d{9}$/
        if (!reg.test(value)) {
          callback(new Error('请输入有效的手机号码'))
        }
      }
      callback()
    }
    return {
      uploadPaths,
      picture: [],
      galleryFileList: [],
      mcategory: [],
      cList: {},
      checked: false,
      dataForm: {
        id: undefined,
        name: undefined,
        nickName: undefined,
        mcategoryId: undefined,
        mechanismType: undefined,
        address: undefined,
        legalPerson: undefined,
        telephone: undefined,
        qualifications: [],
        integralAmountAll: undefined,
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        street: undefined,
        longitude: undefined,
        latitude: undefined,
        affiliation: undefined,
        level: undefined,
        checkWord: undefined,
        certification: []
      },

      rules: {
        name: [{ required: true, message: '请填写机构名称', trigger: 'blur' }],
        mcategoryId: [{ required: true, message: '请选择机构分类', trigger: 'blur' }],
        provinceId: [{ required: true, message: '请选择省市', trigger: 'blur' }],
        cityId: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        areaId: [{ required: true, message: '请选择区域', trigger: 'blur' }],
        address: [{ required: true, message: '请填写具体位置', trigger: 'blur' }],
        telephone: [
          { required: true, message: '请填写联系手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        legalPerson: [{ required: true, message: '请填写法人姓名', trigger: 'blur' }]
      },
      regionsId: {
        id: 0
      },
      aliQrConfig: {
        value: ''
      },

      provinces: {},
      cities: {},
      areas: {},
      areass: {},
      dialogVisible: false,
      alipayDialogStatus: false,
      recordSn: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // 拉取机构类型
      listAllMCategory()
        .then(response => {
          this.mcategory = response.data.data.mcategory
          this.categorylist = response.data.data.brandList
          for (let i = 0; i < this.categorylist.length; i++) {
            this.cList[this.categorylist[i].value] = this.categorylist[i].label
          }
        })
        .catch(() => {
          this.mcategory = []
        })

      this.dialogStatus = 'create'
      if (this.$route.query.id !== '') {
        this.getPicurl(this.$route.query.id)
      }
      if (this.$route.query.merchanismId !== '') {
        this.mid = this.$route.query.merchanismId
        this.getMechanism()
      }
    },
    getContract() {
      this.dialogVisible = true
    },
    getPicurl(pictureId) {
      queryPicurl({ pictureId: pictureId }).then(response => {
        this.picture = response.data.data.introdecPicture
      })
    },
    getMechanism() {
      queryMechanismMeg({ mid: this.mid }).then(response => {
        this.dataForm = response.data.data.mechanism
        this.dataForm.certification = []
        this.getProvinces()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.certification.length > 0) {
            if (!isNaN(this.dataForm.provinceId) && !isNaN(this.dataForm.cityId) && !isNaN(this.dataForm.areaId)) {
              updateMechanismProxy(this.dataForm).then(response => {
                if (response.data.data.message === 'ok') {
                  this.$alert('更新成功！', {
                    confirmButtonText: '确定',
                    type: 'warning'
                  })
                  this.$router.go(-1)
                } else {
                  this.$alert('提交失败，请重试！', {
                    confirmButtonText: '确定',
                    type: 'warning'
                  })
                  this.$router.go(-1)
                }
              })
            } else {
              this.$alert('区域地址请填写完整！！', {
                confirmButtonText: '确定',
                type: 'warning'
              })
            }
          } else {
            this.$alert('请重新上传资质图片！', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        }
      })
    },
    uploadPicUrl: function(response) {
      this.dataForm.qualifications.push(response.data.url)
    },
    handleImport() {
      console.log('handleImport')
    },
    getProvinces() {
      listAddress({ pid: this.regionsId.id, cid: this.dataForm.provinceId, aid: this.dataForm.cityId }).then(
        response => {
          this.provinces = response.data.data.plist
          this.cities = response.data.data.clist
          this.areas = response.data.data.alist
        }
      )
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.dataForm.certification.push(response.data.url)
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.dataForm.qualifications.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.dataForm.qualifications[i] === url) {
          this.dataForm.qualifications.splice(i, 1)
        }
      }
    },
    provinceChange(val) {
      if (val === undefined) {
        return
      }
      this.cities = {}
      this.dataForm.cityId = undefined
      this.areas = {}
      this.dataForm.areaId = undefined
      listSubRegion({ id: val }).then(response => {
        this.cities = response.data.data
      })
    },
    cityChange(val) {
      if (val === undefined) {
        return
      }
      this.areas = {}
      this.dataForm.areaId = undefined
      listSubRegion({ id: val }).then(response => {
        this.areas = response.data.data
      })
    },
    areaChange(val) {
      if (val === undefined) {
        return
      }
      this.areass = {}
      this.dataForm.street = undefined
    },
    areasChange(val) {},
    /* 重置表单 */
    resetForm() {
      this.resetDataForm()
      this.resetUserForm()
    },
    resetDataForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        nickName: undefined,
        mechanismType: undefined,
        address: undefined,
        legalPerson: undefined,
        telephone: undefined,
        startTime: undefined,
        endTime: undefined,
        qualifications: [],
        integralAmountAll: undefined,
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        street: undefined,
        longitude: undefined,
        latitude: undefined
      }
    },
    resetUserForm() {
      this.userForm = {
        username: undefined,
        mobile: undefined,
        integral: undefined,
        balance: undefined,
        exchangeNum: undefined
      }
    },
    queryalipaystatus() {
      if (this.recordSn !== '') {
        queryalipaystatus(this.recordSn)
          .then(response => {
            var orderStatus = response.data.data.orderStatus
            if (orderStatus === 'SUCCESS') {
              this.timeOut = ''
              this.aliQrConfig.value = ''
              this.resetForm()
              this.dialogChargeFormVisible = false
              this.alipayDialogStatus = false
              this.getList()
              this.fullscreenLoading = false
              this.chargeButton = false
              this.$notify({
                title: '成功',
                message: '充值成功',
                type: 'success',
                duration: 3000
              })
            } else if (orderStatus === 'WAIT_PAY') {
              this.timeOut = setTimeout(() => {
                this.queryalipaystatus()
              }, 3000)
            }
          })
          .catch(() => {
            this.timeOut = ''
            this.resetForm()
            this.dialogChargeFormVisible = false
            this.alipayDialogStatus = false
            this.getList()
            this.fullscreenLoading = false
            this.chargeButton = false
            this.$notify({
              title: '错误',
              message: '充值失败',
              type: 'error',
              duration: 1000
            })
          })
      }
    },
    uploadAvatar(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorageFile(formData)
        .then(res => {
          this.dataForm.avatar = res.data.data.url
        })
        .catch(() => {
          this.$message.error('上传失败，请重新上传')
        })
    },
    handleUpdate() {
      this.resetForm()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.dataForm = this.instituteForm
      this.cities = {}
      this.areas = {}
      listSubRegion({ id: this.dataForm.provinceId }).then(response => {
        this.cities = response.data.data
      })
      listSubRegion({ id: this.dataForm.cityId }).then(response => {
        this.areas = response.data.data
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

      this.galleryFileList = []
      for (var i = 0; i < this.dataForm.certification.length; i++) {
        this.galleryFileList.push({
          url: this.dataForm.certification[i]
        })
      }
    },
    createRecordSn() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var ss = date.getMilliseconds()
      if (ss < 10) {
        ss = '00' + ss
      } else if (ss < 100) {
        ss = '0' + ss
      }
      // var result = Y.to + M + D + h + m + s + ss;
      var result =
        Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString()
      console.log('result = ' + result)
      return result
    }
    /* 更新数据 */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.regist-container {
  width: 100%;
  // height: 100%;
  background-color: white;
  .registpage-top {
    // height: 5%;
    height: 50px;
    width: 80%;
  }
  .regist-div {
    width: 60%;
    height: 90%;
    margin-left: 20%;
    background-color: #eee;
    border: 1px solid #f2ddaf;
  }
}
.dialog-footer {
  margin-bottom: 20px;
}
.registpage-footer {
  height: 80px;
  // height: 5%;
}
.certification-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.certification-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.certification-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.certification {
  width: 120px;
  height: 120px;
  display: block;
}
.regist {
  width: 80%;
  height: 80%;
  margin: auto;
}
.dataForm-title {
  font-size: 26px;
  // font-weight: 400;
  color: #000;
  margin: 40px auto 40px auto;
  text-align: center;
  font-weight: bold;
}
.contract {
  margin-left: 20px;
  color: blue;
  cursor: pointer;
  float: right;
}
.contract-dialog {
  white-space: pre-wrap;
  word-wrap: break-word;
  width: 80%;
  margin: auto;
  margin-top: 20px;
  line-height: 25px;
  font-size: 14px;
}
</style>
